<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
          jvm锁优化 - Ethan的博客 | Ethan&#39;s Blog
        
    </title>

    <link rel="canonical" href="http://reflectyi.gitee.io/myblog/myblog/2016/10/01/jvm/并发/锁优化/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/myblog/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/myblog/css/hux-blog.min.css">

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/myblog/css/highlight.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/myblog/">Hi,Ethan</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/myblog/">首页</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/myblog/about/">目录</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/archives/">时间轴</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/tags/">标签</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    
<!-- Image to hack wechat -->
<!-- <img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0"> -->
<!-- <img src="{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}" width="0" height="0"> -->

<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        background-image: url('/myblog/img/home-bg.jpg')
    }
</style>
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#Thread" title="Thread">Thread</a>
                        
                    </div>
                    <h1>jvm锁优化</h1>
                    <h2 class="subheading">自旋锁、轻量级锁、偏向锁(对象头、CAS)</h2>
                    <span class="meta">
                        Posted by Ethan on
                        2016-10-01
                    </span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <h2 id="锁优化"><a href="#锁优化" class="headerlink" title="锁优化"></a>锁优化</h2><h3 id="一、自旋锁和自适应锁"><a href="#一、自旋锁和自适应锁" class="headerlink" title="一、自旋锁和自适应锁"></a>一、自旋锁和自适应锁</h3><ul>
<li>概述：挂起和恢复线程都需要在内核态和用户态之间切换，但共享状态数据锁定时间又很短，不值来回切换。<ul>
<li>如果系统又多个物理核心，那么并发情况下，让请求锁的<code>线程B</code>不放弃处理器执行时间，查看能否很快获取到锁，让<code>线程B</code>执行忙循环(自旋)，被称之为自旋锁</li>
<li>自旋锁不能取代阻塞，等待一定限度，超过限度仍没有获取到锁，那就采用传统方式挂起(浪费了更多的资源)</li>
</ul>
</li>
<li>JDK1.6自适应的自旋锁<ul>
<li>自旋时间不固定，由前一次在同一个锁上的自旋时间及锁的拥有者状态决定的。</li>
<li>如果上一次在同一个锁对象上，自旋等待获取成功，且持有锁的线程在运行。那么jvm会认为本次仍然能成功，进而允许自旋锁等待更长的时间 </li>
<li>如果对于某个锁，自旋很少获得成功。那么以后获取该锁时，可能会放弃自旋锁<h3 id="二、锁消除"><a href="#二、锁消除" class="headerlink" title="二、锁消除"></a>二、锁消除</h3></li>
</ul>
</li>
<li>概述：jvm即时编译器在运行时，对一些代码上要求同步，但被检测到不存在共享数据竞争的锁进行消除。<ul>
<li>如果判断一段代码，堆上的所有数据都不会逃逸出去从而被其他线程访问到，那么就把它们当做栈上数据，认为线程私有 </li>
<li>方法内部创建锁对象，这个对象外部不能访问，且方法结束，对象结束<h3 id="三、锁粗化"><a href="#三、锁粗化" class="headerlink" title="三、锁粗化"></a>三、锁粗化</h3></li>
</ul>
</li>
<li>概述：尽量让同步代码块小，这样等待线程可以尽快拿到锁。<ul>
<li>但是频繁的加锁、解锁，造成资源浪费。jvm探测到有这样连续对同一个对象加锁，会把加锁的同步范围扩展到整个操作的外部。<h3 id="四、轻量级锁"><a href="#四、轻量级锁" class="headerlink" title="四、轻量级锁"></a>四、轻量级锁</h3></li>
</ul>
</li>
<li>1、对象头(Object Header)<ul>
<li>一部分，对象存储自身的运行时数据(Mark-world,数组)<ul>
<li>哈希码(HashCode)、GC分代年龄、偏向线程ID、偏向时间戳、指向锁记录的指针、指向重量级锁的指针</li>
<li>实现偏向锁和轻量级锁的关键</li>
</ul>
</li>
<li>另一部分，存储指向方法区对象类型数据的指针，</li>
<li>如果是数组还有额外的部分存储数组长度</li>
</ul>
</li>
<li>2、CAS轻量级加锁<ul>
<li>代码进入同步块时，对象没有被锁定，jvm现在当前线程的栈帧中建立一个名为<code>锁记录(Lock Record)</code>的空间，用于存储锁对象目前<code>Mark-World</code>的拷贝</li>
<li>jvm使用CAS尝试将对象头中的<code>Mark-World</code>的指针，指向栈帧中的<code>锁记录(Lock Record)</code><ul>
<li>更新成功，并且将<code>Mark-World</code>的锁标志位修改为00，表示轻量级锁定。那么这个obj也就和对象栈帧中的 <code>锁记录(Lock Record)</code>建立了联系</li>
<li>更新失败，jvm先检查该对象的<code>Mard-World</code>是不是指向本线程的栈帧内的<code>锁记录(Lock Record)</code>。如果是，那就继续执行。如果不是，就转化为重量级锁，线程阻塞</li>
</ul>
</li>
</ul>
</li>
<li>3、CAS轻量级解锁<ul>
<li>如果对象的<code>mark-world</code>指向栈帧中的<code>锁记录(Lock Record)</code>，那就用CAS把当前对象的<code>Mark-World</code>和栈帧中<code>锁记录(Lock Record)</code>内容替换回来<ul>
<li>替换成功，同步完成</li>
<li>替换失败，说明有其他线程尝试获取该锁，那就释放锁的同时，唤醒被挂起的线程。</li>
</ul>
</li>
</ul>
</li>
<li>总结：轻量级锁提升性能靠的是，对于绝大部分的锁，在整个存在周期中是不存在竞争的<ul>
<li>如果没有竞争CAS回避了互斥量的开销</li>
<li>如果有竞争，会比重量级锁开销更大<h3 id="五、偏向锁"><a href="#五、偏向锁" class="headerlink" title="五、偏向锁"></a>五、偏向锁</h3></li>
</ul>
</li>
<li>概述：这个锁会偏向于第一个获取它的线程，如果接下来的执行过程，该锁没有被其他的线程获取，则持有该偏向锁的线程无需在进行同步。</li>
<li>1、jvm启用偏向锁<ul>
<li>锁对象第一次被线程获取的时候，会把对象头中的标志位设置为“01”，即偏向模式</li>
<li>CAS操作会把获取到锁的线程ID记录在对象的<code>Mark-World</code><ul>
<li>如果操作成功，持有偏向锁的线程以后每次进入这个锁同步块的时候，都不用进行任何同步操作</li>
<li>当有另一个线程尝试获取该锁的时候，偏向模式结束  </li>
</ul>
</li>
</ul>
</li>
<li>2、偏向锁可以提高带有同步，但无竞争的程序性能。但不一定总是有利，如果锁总是被多个不同线程访问那么性能就不高</li>
</ul>


                <hr>

                

                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/myblog/2016/10/01/jvm/并发/java内存模型/" data-toggle="tooltip" data-placement="top" title="java内存模型">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/myblog/2016/10/01/jvm/memory/HotSpot算法实现/" data-toggle="tooltip" data-placement="top" title="HotSpot算法实现概述">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>
    <!-- Side Catalog Container -->
        
            <div class="
                col-lg-2 col-lg-offset-0
                visible-lg-block
                sidebar-container
                catalog-container">
                <div class="side-catalog">
                    <hr class="hidden-sm hidden-xs">
                    <h5>
                        <a class="catalog-toggle" href="#">CATALOG</a>
                    </h5>
                    <ul class="catalog-body"></ul>
                </div>
            </div>
        

    <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/myblog/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#Thread" title="Thread">Thread</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li>
                    
                        <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li>
                    
                        <li><a href="#" target="_blank">Foo</a></li>
                    
                        <li><a href="#" target="_blank">Bar</a></li>
                    
                        <li><a href="#" target="_blank">Example Friends</a></li>
                    
                        <li><a href="#" target="_blank">It helps SEO</a></li>
                    
                </ul>
                
            </div>

        </div>
    </div>
</article>




<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "hexo-theme-huxblog";
    var disqus_identifier = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/并发/锁优化/";
    var disqus_url = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/并发/锁优化/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'always',
          placement: 'right',
          icon: '#'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                
                    <li>
                        <a target="_blank" href="https://www.facebook.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://github.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; Hi,Ethan 2019 
                    <br>
                    Theme by <a href="http://huangxuan.me">Hux</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    Ported by <a href="http://blog.kaijun.rocks">Kaijun</a> | 
                    <iframe
                        style="margin-left: 2px; margin-bottom:-5px;"
                        frameborder="0" scrolling="0" width="91px" height="20px"
                        src="https://ghbtns.com/github-btn.html?user=kaijun&repo=hexo-theme-huxblog&type=star&count=true" >
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/myblog/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/myblog/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/myblog/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://reflectyi.gitee.io/myblog/myblog/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-49627206-1';
    var _gaDomain = 'huangxuan.me';

    // Originial
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->

<script>
    // dynamic User by Hux
    var _baId = '4cc1f2d8f3067386cc5cdb626a202900';

    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<!-- Side Catalog -->

<script type="text/javascript">
    function generateCatalog (selector) {
        var P = $('div.post-container'),a,n,t,l,i,c;
        a = P.find('h1,h2,h3,h4,h5,h6');
        a.each(function () {
            n = $(this).prop('tagName').toLowerCase();
            i = "#"+$(this).prop('id');
            t = $(this).text();
            c = $('<a href="'+i+'" rel="nofollow">'+t+'</a>');
            l = $('<li class="'+n+'_nav"></li>').append(c);
            $(selector).append(l);
        });
        return true;    
    }

    generateCatalog(".catalog-body");

    // toggle side catalog
    $(".catalog-toggle").click((function(e){
        e.preventDefault();
        $('.side-catalog').toggleClass("fold")
    }))

    /*
     * Doc: https://github.com/davist11/jQuery-One-Page-Nav
     * Fork by Hux to support padding
     */
    async("/myblog/js/jquery.nav.js", function () {
        $('.catalog-body').onePageNav({
            currentClass: "active",
            changeHash: !1,
            easing: "swing",
            filter: "",
            scrollSpeed: 700,
            scrollOffset: 0,
            scrollThreshold: .2,
            begin: null,
            end: null,
            scrollChange: null,
            padding: 80
        });
    });
</script>





<!-- Image to hack wechat -->
<img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
